package org.example.com.editor.command.workspaceCommand;

import org.example.com.editor.command.Command;
import org.example.com.editor.ui.ConsoleUI;
import org.example.com.editor.workspace.Workspace;

import java.io.IOException;
import java.util.List;
import java.util.Scanner;

public class ExitCommand implements Command {

    @Override
    public void execute(Workspace workspace, ConsoleUI ui) {
        Scanner scanner = ui.getScanner();
        List<String> files = workspace.getOpenedFiles();
        for(String filePath:files){
            try {
                if(workspace.isFileModified(filePath)){
                    ui.printError("文件 " + filePath + " 有未保存的修改，是否保存？(y/n)");
                    while(true){
                        String choice = scanner.nextLine();
                        if(choice.equals("y")){
                            workspace.saveFile(filePath);
                            ui.printInfo("已保存文件：" + filePath);
                            break;
                        }else if(choice.equals("n")){
                            ui.printInfo("未保存文件，直接退出：" + filePath);
                            break;
                        }else{
                            ui.printError("无法识别的选项,请重新输入");
                        }
                    }
                }
            } catch (IOException e) {
                ui.printError("保存文件失败：" + e.getMessage());
            }
        }

        try {
            workspace.saveState();
        } catch (IOException e) {
            ui.printError("保存工作区状态失败：" + e.getMessage());
        }

        ui.printInfo("退出程序...");
        System.exit(0);  // 后续替换为优雅退出（处理未保存文件）
    }

    @Override
    public String getName() {
        return "exit";
    }
}